<?php
namespace app\api\controller;

use app\api\model\FreeGroupMember;
use app\api\model\WxsoftGrouptourFeedback;
use app\common\controller\Api;
use app\api\controller\Common;
use app\common\controller\Token as UserToken;//加签+鉴权
use app\api\model\GroupToursLine as GT;
use app\api\model\Order as OrderModel;
use app\api\model\FreeGroup as FG;
use app\wap\controller\Grouptoursline as WapGT;
use app\wap\controller\Notify;
use think\Config;
use think\db;
use think\Exception;
use think\log;

class GroupToursWxSoft extends Api
{
    use UserToken;
    protected $notice_email = 'david@kuaibangxing.com';
    protected $beforeActionList = [
        //所有方法进行加签
//        'checkSign'=>[
//            'except'=>'getapisign',//除了获取签名的方法外，其他均需要签名
//        ],
        'checkUserToken'=>[
            'only'=>'order,userinfo,orderlist,integrallist,userprofit,profitlist,applycashout,realauth,record,orderdetail,delorder,createfreegroup,joinfreegroup,outfreegroup,freegrouplistbymemberid,publishfreegroup,joingreegroupv2',
        ]
    ];
    //初始化
    public function _initialize()
    {
        header('Access-Control-Allow-Origin:*');
    }
    //获取拼游列表 分页+搜索
    public function getList()
    {
        $post = request()->post();
        //关键字
        $keyword = $post['keyword']??'';
        $page = $post['page']??1;
        $offset = $post['offset']??10;
        $model = new GT();
        list($total,$list) = $model->getList($keyword,$page,$offset,'wxSoft');
        //封装线路的成团情况 to do ...
        $exchange = db('exchange')->select();
        foreach ($list as $key=>$value){
            unset($list[$key]['from_address_json'],$list[$key]['to_address_json']);
            $exchange_rate = 1;
            foreach ($exchange as $e_v){
                if($e_v['currency_code']==$value['currency']){
                    $exchange_rate = $e_v['exchange_rate'];
                }
            }
            $list[$key]['person_price_currency'] = ((new GT())->getSymbolByCurrency($value['currency']))['currSymbol'];
            $list[$key]['person_price_cny'] = sprintf('%.0f',$value['person_price']*$exchange_rate);
            $list[$key]['groupOrder'] = $model->getOrderToursGroup($value['line_id']);
            //详情图片地址域名替换
            $list[$key]['img'] = (new GT())->replaceOssImgDomain($list[$key]['img']);
        }
        $data['total'] = $total;
        $data['totalPage'] = ceil($total/$offset);
        $data['curPage'] = (int)$page;
        $data['offset'] = (int)$offset;
        $data['list'] = $list;
        return json_encode(['code'=>200,'msg'=>'success','data'=>$data]);
    }

    //获取拼游列表 分页+搜索
    public function getRecGroupList()
    {
        $model = new GT();
        $data = $model->getRecGroupList();
        return json_encode(['code'=>200,'msg'=>'success','data'=>$data]);
    }
    //拼游详情
    public function getDetail()
    {
        $post = request()->post();
        $line_id = $post['id']??0;
        $cityName = $post['city_name']??'';
        $model = new GT();
        $detail = $model->getDetail($line_id,'wxSoft',true,$cityName);
        if(empty($detail)){
            return json_encode(['code'=>404,'msg'=>'data is empty']);
        }else{
            //成团情况 to do ....
            $exchange = db('exchange')->select();
            $exchange_rate = 1;
            foreach ($exchange as $e_v){
                if($e_v['currency_code']==$detail['currency']){
                    $exchange_rate = $e_v['exchange_rate'];
                }
            }
            $detail['person_price_cny'] = sprintf('%.0f',$detail['person_price']*$exchange_rate);
            $detail['busy_person_price_cny'] = sprintf('%.0f',$detail['busy_person_price']*$exchange_rate);
            $detail['hotel_unit_price_cny'] = sprintf('%.0f',$detail['hotel_unit_price']*$exchange_rate);
            $detail['busy_hotel_unit_price_cny'] = sprintf('%.0f',$detail['busy_hotel_unit_price']*$exchange_rate);
            $detail['packages'] = $model->getPackageSpecByLineId($line_id,$exchange_rate);
            $detail['busyPackages'] = $model->getPackageSpecByLineId($line_id,$exchange_rate,true);
            $groupOrder = $model->getOrderToursGroup($line_id);
            $detail['groupOrder'] = $groupOrder;
            //返现规则
            $detail['cashBackRules'] = $model->getCashBackRules($detail['person_price'],$line_id);
            $detail['inviteMemberTitle'] = '1人保证出行！7座小车！上门接送！';
            //详情图片地址域名替换
            $detail['img'] = (new GT())->replaceOssImgDomain($detail['img']);
            $detail['product_info']['goods_video'] = (new GT())->replaceOssImgDomain($detail['product_info']['goods_video']);
            if(!empty($detail['product_info'])){
                $detail['product_info']['goods_introduce'] = (new GT())->replaceOssImgDomain($detail['product_info']['goods_introduce']);
                $detail['product_info']['goods_image'] = (new GT())->replaceOssImgDomain($detail['product_info']['goods_image']);
            }
            //返回推广可获得的金额
            $detail['shareCashBack'] = Config('shareCashBackRate')*$detail['person_price'];
            $partySize = array_column($detail['cashBackRules'],'people_num');
            $detail['minPartySize'] = $detail['maxPartySize'] = 0;
            if(!empty($partySize)){
                $detail['minPartySize'] = min($partySize);
                $detail['maxPartySize'] = max($partySize);
            }
            unset($detail['from_address_json'],$detail['to_address_json']);
            return json_encode(['code'=>200,'msg'=>'success','data'=>$detail]);
        }
    }
    //团详情
    public function getGroupDetail()
    {
        $post = request()->post();
        $id = $post['id']??'';
        $userKbxId = $post['userKbxId']??'';
        if(empty($id)) return json_encode(['code'=>-400,'msg'=>'拼游报团信息有误']);
        $groupInfo = (new KbxOrder())->getGrouptoursGroupInfo($id,$userKbxId);
        if(!is_array($groupInfo) || !empty($groupInfo['msg'])){
            return json_encode(['code'=>-404,'msg'=>$groupInfo['msg']]);
        }else{
            //判断当前团期的淡旺季
            $groupInfo['is_busy'] = false;
            if(!empty($startDate)){
                $groupInfo['is_busy'] = $this->checkIsBusyByGroupInfo($groupInfo);
            }
            //封装用户信息和返现金额
            $groupInfo = $this->packageBooker($groupInfo);
            $groupInfo = $this->calculateCashBackByPartySize($groupInfo);
            return json_encode(['code'=>200,'msg'=>'success','data'=>$groupInfo]);
        }
    }
    //下单
    public function order()
    {
        $post = request()->post();
        //检验必须参数 to do ...
        $match_arr = array(
            "line_id",
            "consumer_phone",
            "adultPassengers"
        );
        $match_res = (new WapGT())->match_post($match_arr,$post);
        if($match_res['code']!=200){
            return json_encode($match_res);
        }
        $post['member_id'] = $this->member_id;
        //推广人id
        $post['spread_member_id'] = $post['spread_member_id']??0;
        //发送到订单系统
        $kbxOrder = new KbxOrder();
        //如果用户发起拼团
        $order_data = [];
        if(!isset($post['groupOrderId']) || empty($post['groupOrderId'])){
            $startDate = $post['startDate']??"";
//            $person_id = $post['person_id']??0;
//            $personInfo = db("person")->find($person_id);
            if(empty($startDate)){
                return json_encode(['code'=>-400,'msg'=>'请选择出行时间']);
            }
//            if(empty($personInfo)){
//                return json_encode(['code'=>-400,'msg'=>'请选择拼团类型']);
//            }
            $personInfo = [];
            $model = new GT();
            $detail = $model->getDetail($post['line_id'],'wxSoft',true);
            if(empty($detail)){
                return json_encode(['code'=>-400,'msg'=>'拼团线路有误']);
            }
            $order_data = (new WapGT())->getOrderDataByGroupLineDetail($startDate,$personInfo,$post,$detail);
        }
        $res = $kbxOrder->addCustomerByMall($post,$order_data);
//        var_dump($res);exit;
        //解析订单系统的结果
        if(isset($res['carPoolOrder']['_id']) && !empty($res['carPoolOrder']['_id'])){
            $data = ['code'=>200,'msg'=>'success','data'=>$res];
            //给后台管理员发邮件
            $orderDate = array(
                'line_id'=>$res['carPoolOrder']['line'],
                'member_id'=>$res['personalOrder']['booker']['memberId'],
                'order_no'=>$res['personalOrder']['orderNo'],
//                'e_mail'=>$res['personalOrder']['consumer']['contact']['email'],
                'phone'=>$res['personalOrder']['consumer']['contact']['phone'],
                "travel_date"=>$res['carPoolOrder']['details']['startDate'],
            );
            (new Notify())->gyouxiang($orderDate,"carPool",'新小V拼游订单通知【未支付】');
            //推广人员记录佣金
            (new OrderModel())->shareCashBackToSpreadMember($post,$res);
        }elseif(isset($res['msg'])){
            $data = ['code'=>-404,'msg'=>$res['msg']];
        }else{
            $data = ['code'=>-404,'msg'=>'加入拼团失败，请稍后重试！'];
        }
        return json_encode($data);
    }
    //个人中心
    public function userInfo()
    {
        $member_id = $this->member_id;

        $member = db('member')
            ->field("member_id,thumb,member_username,member_nickname,member_integral,member_money,is_apply,member_pcode")
            ->find($member_id);
        if(empty($member_id) || empty($member)){
            return json_encode(['code'=>-201,'msg'=>'请前往个人中心授权']);
        }
        $member['headimg'] = '';
        if(!empty($member['thumb'])){
            $thumb = db('attachment')->find($member['thumb']);
            $member['headimg'] = $thumb['filepath']??"";
            $member['headimg'] = str_replace('http://','https://',$member['headimg']);
        }
        $member['partner_id'] = 'kbx';
        if($member['member_pcode']==1159){
            $member['partner_id'] = 'fl';
        }
        //预计收益 未入账的佣金
        $distributiondetails = db('distributiondetails')
            ->field('sum(money) as money')
            ->where(['member_id'=>$member_id,'enter_account'=>0])
            ->find();
        $member['expect_money'] = $distributiondetails['money']??0;
        return json_encode(['code'=>200,'msg'=>'获取个人信息成功','data'=>$member]);
    }
    //订单列表
    public function orderList()
    {
        $post = request()->post();
        $status = $post['status']??0;
        $member_id = $this->member_id;
        $member = db('member')->find($member_id);
        if(empty($member_id) || empty($member)){
            return json_encode(['code'=>-201,'msg'=>'请前往个人中心授权']);
        }
//        $member['kbx_id'] = '5cad4c910305bfd5275e57cb';
        if(empty($member['kbx_id'])){
            return json_encode(['code'=>-201,'msg'=>'请前往个人中心授权']);
        }
        $member_kbx_id = $member['kbx_id'];
        $res = (new KbxOrder())->getGrouptoursOrderList($member_kbx_id);
        if(!is_array($res)){
            return json_encode(['code'=>-400,'msg'=>'获取订单列表数据失败']);
        }else{
            $list = [];
            //解析数据
            foreach ($res as $key=>$value){
                $orderStatus = $value['orderStatusForUser'];
                $paymentStatus = $value['status']['paymentStatus'];
                $value['displayedStatusStr'] = (new KbxOrder())->getDisplayOrderStateTitle($orderStatus,$paymentStatus);
                $orderStatus = (new KbxOrder())->getStatusByOrderStatus($orderStatus,$paymentStatus);
                if(empty($status) || $orderStatus==$status){
                    $value['order_status'] = $orderStatus;
                    $list[] = $value;
                }
            }
            return json_encode(['code'=>200,'msg'=>'success','data'=>$list]);
        }
    }

    //积分列表
    public function integralList()
    {
        $post = request()->post();
        $member_id = $this->member_id;

        $page = $post['page']??1;
        $offset = $post['offset']??10;
        $total = db('member_integrallog')
            ->where('member_id',$member_id)
            ->count();
        $list = db('member_integrallog')
            ->where('member_id',$member_id)
            ->order('create_time desc')
            ->page($page,$offset)
            ->select();

        $data['total'] = $total;
        $data['totalPage'] = ceil($total/$offset);
        $data['curPage'] = (int)$page;
        $data['offset'] = (int)$offset;
        $data['list'] = $list;
        return json_encode(['code'=>200,'msg'=>'获取积分列表成功','data'=>$data]);

    }

    //我的收益
    public function userProfit()
    {
        $member_id = $this->member_id;

        //获取用户金额
        $money = db('member')->field('member_money')->find($member_id);
        //是否实名认证
        $real_auth = db('member_real')->alias('a')
            ->where('a.member_id',$member_id)
            ->join('transferchannel b','b.channel_id=a.channel_id')
            ->field('a.*,b.name as channel_name ')
            ->find();
        //预计收益 未入账的佣金
        $distributiondetails = db('distributiondetails')
            ->field('sum(money) as money')
            ->where(['member_id'=>$member_id,'enter_account'=>0])
            ->find();
        return json_encode(['code'=>200,'msg'=>'获取我的收益成功','data'=>[
            'money'       =>  $money['member_money']??0,
            'expect_money'=>  $distributiondetails['money']??0,
            'real_auth'   =>  $real_auth
        ]]);
    }

    //收益列表
    public function profitList()
    {
        $post = request()->post();
        $member_id = $this->member_id;

        $page = $post['page']??1;
        $offset = $post['offset']??10;

        $total =  db('distributiondetails dd')
            ->where('member_id',$member_id)
            ->count();
        $list = db('distributiondetails dd')
            ->where('member_id',$member_id)
            ->order('id desc')
            ->page($page,$offset)
            ->select();
        foreach ($list as $k=>$v) {
            $list[$k]['state_title'] = $v['enter_account']>0?"已入账":"待入账";
            $list[$k]['goods_name'] = $v['order_name'];
            if($v['consumption_goods']>0){
                $goods= db('goods')->where('goods_id',$v['consumption_goods'])->field("goods_name")->find();
                $list[$k]['goods_name'] = $goods['goods_name'];
            }
            $member = $where = [];
            if($v['consumption_member_id']){
                $where['m.member_id'] = $v['consumption_member_id'];
            }elseif($v['consumption_member_username']){
                $where['m.member_username'] = $v['consumption_member_username'];
            }

            if(!empty($where)){
                $member = db('member m')->field('m.member_nickname,a.filepath as headming')
                    ->where($where)
                    ->join('attachment a','a.id = m.thumb','left')
                    ->find();
            }
            $list[$k]['consumption_member_name'] = $member['nickname']??'路人';
            $list[$k]['consumption_headimg'] = $member['headmimg']??Config::get('default_member_headimg');
            $list[$k]['consumption_time'] = date('Y-m-d H:i:s',$v['consumption_time']);
        }

        $data['total'] = $total;
        $data['totalPage'] = ceil($total/$offset);
        $data['curPage'] = (int)$page;
        $data['offset'] = (int)$offset;
        $data['list'] = $list;
        return json_encode(['code'=>200,'msg'=>'获取收益列表成功','data'=>$data]);
    }

    //申请提现
    public function applyCashOut(){
        $member_id = $this->member_id;
        $post=request()->post();
        $money = $post['money']??0;
        if (empty($money)) return json_encode(['code'=>-112,'msg'=>'提现金额不能为空']);
        $forward = db('putforward')->where([ 'member_id'=>$member_id])->order('time desc')->find();
        if (($forward['time']+300)>time()){
            return json_encode(['code'=>-113,'msg'=>'300秒内只能发起一次提现']);
        }

        db::startTrans();
        try{
            db('member')->where('member_id',$member_id)->setDec('member_money', (float)$money);
            db('putforward')->insert([
                'member_id'=>$member_id,
                'money'=>$money,
                'type'=>0,
                'state'=>1,
                'time'=>time()
            ]);
            // 提交事务
            db::commit();
            return json_encode(['code'=>200,'msg'=>'提交申请成功']);
        } catch (\Exception $e) {
            // 回滚事务
            db::rollback();
            trace('参数错误 写入数据失败\r\n'.'error:'.$e->getMessage());
            return json_encode(['code'=>-400,'msg'=>'请求频繁，请稍后重试']);
        }
    }

    //实名认证
    public function realAuth()
    {
        $member_id = $this->member_id;
        $post=request()->post();
        if (empty($post['name'])) return json_encode(['code'=>-201,'msg'=>'请填写真实姓名']);
        if (empty($post['phone'])) return json_encode(['code'=>-201,'msg'=>'请填写手机号']);
        if (empty($post['channel_id'])) return json_encode(['code'=>-201,'msg'=>'请选择收款方式']);
        if (empty($post['account'])) return json_encode(['code'=>-201,'msg'=>'请填写转账账号信息']);
        //是否已认证
        $has_auth = db('member_real')->where('member_id',$member_id)->find();
        $upd_data = [
            'member_id'=>$member_id,
            'name'=>$post['name'],
            'wechat'=>$post['wechat']??"",
            'phone'=>$post['phone'],
            'channel_id'=>$post['channel_id'],
            'account'=>$post['account'],
            'message'=>$post['message']??'',
        ];
        if(!empty($has_auth)){
            $res = db('member_real')->where('real_id',$has_auth['real_id'])->update($upd_data);
        }else{
            $res = db('member_real')->insert($upd_data);
        }

        if($res!==false){
            return json_encode(['code'=>200,'msg'=>'提交认证信息成功','data'=>$post]);
        }else{
            return json_encode(['code'=>-400,'msg'=>'操作频繁，请稍后重试']);
        }
    }

    //获取收款渠道
    public function channel(){
        $list = db('transferchannel')
            ->where('state',0)
            ->field('channel_id as id,name')
            ->select();
        return json_encode(['code'=>200,'msg'=>'获取收款渠道列表成功','data'=>$list]);
    }

    //提现记录
    public function record()
    {
        $member_id = $this->member_id;
        $post = request()->post();
        $page = $post['page']??1;
        $offset = $post['offset']??10;
        $total = db('putforward')->where(['member_id'=>$member_id])->count();
        $list = db('putforward')
            ->field('id,money,FROM_UNIXTIME(time,"%Y-%m-%d %H:%i:%s") as time ,state')
            ->where([ 'member_id'=>$member_id])
            ->order('time desc')
            ->page($page,$offset)
            ->select();

        $data['total'] = $total;
        $data['totalPage'] = ceil($total/$offset);
        $data['curPage'] = (int)$page;
        $data['offset'] = (int)$offset;
        $data['list'] = $list;
        return json_encode(['code'=>200,'msg'=>'success','data'=>$data]);
    }

    //获取产品群二维码
    public function getGroupQrcode()
    {
        $post = request()->post();
        $id = $post['id']??0;
        //默认前期只维护第一个群
        $default_qrcode = db('grouptour_qrcode')->find();
        $id = $default_qrcode['grouptour_id'];

        if(empty($id)) json_encode(['code'=>-400,'msg'=>'产品信息有误']);

        $res = db('grouptour_qrcode g')
            ->field('title,desc,expire_time,a.filepath as qrcode')
            ->join('attachment a','a.id=g.qrcode','left')
            ->where($where)
            ->order('expire_time desc')
            ->find();
        if(!empty($res)){
            //替换图片地址
            $res['qrcode'] = (new GT())->replaceOssImgDomain($res['qrcode']);
            return json_encode(['code'=>200,'msg'=>'success','data'=>$res]);
        }else{
            return json_encode(['code'=>-400,'msg'=>'该产品暂未组建群组,请耐心等候']);
        }
    }

    //已支付拼团订单接口【备用】
    public function orderDetailPaid()
    {
        $post = request()->post();
        $orderNo = $post['order_no'];
        $member_id = $this->member_id;
        $member = db("member")->where("member_id",$member_id)->field("member_username")->find();
        $kbxToken = new KbxToken();
        $user = $kbxToken->kbxUser($member['member_username']);
        if(empty($user['id']) && empty($member['kbx_id'])) return json_encode(['code'=>-400,'找不到用户信息']);
        $user_kbx_id = $user['id']??$member['kbx_id'];
        $res = (new KbxOrder())->getGrouptoursOrderInfo($user_kbx_id,$orderNo);
        if(!empty($res['msg'])) return json_encode(['code'=>-400,'msg'=>$res['msg']]);
        //拼团订单详情
        $res = (new KbxOrder())->formatOrder($res,3);
        return json_encode(['code'=>200,'msg'=>'success','data'=>$res]);
    }

    //拼游订单详情接口【由nopay改为所有】
    public function orderDetail()
    {
        $post = request()->post();
        $orderNo = $post['order_no'];

        $kbxToken = new KbxToken();
        $res = (new KbxOrder())->kbx_order_by_no($orderNo);
        $res = $kbxToken->object_array($res);
        if(!empty($res['msg'])) return json_encode(['code'=>-400,'msg'=>$res['msg']]);
        //判断状态
        $orderStatus = $res['status']['orderStatus'];
        $paymentStatus = $res['status']['paymentStatus'];
        $displayedStatusStr = (new KbxOrder())->getDisplayOrderStateTitle($orderStatus,$paymentStatus);
        $resOrder = [];

        $resOrder['order_id'] = $res['_id']??"";
        $resOrder['orderNo'] = $res['orderNo'];
        $resOrder['orderName'] = $res['carPoolOrder']['name'];
        $resOrder['orderType'] = $res['orderType'];
        $resOrder['cityName'] = $res['carPoolOrder']['details']['fromCity']['name'];
        $resOrder['displayedStatusStr'] = $displayedStatusStr;
        $resOrder['isdelete'] = isset($res['isDelete']) ? $res['isDelete'] : 0;
        $resOrder['initAt'] = "北京时间".date("Y-m-d H:i:s",strtotime($res['createdAt']));
        $resOrder['foldMoney'] = $res['payments']['foldMoney'];
        $resOrder['orderuser'] = [
            "Phone"=>$res['customer']['username'],
            "email"=>$res['customer']['email']??"",
            "firstname"=>$res['customer']['profile']['name'],
            "surname"=>'',
        ];
        $resOrder['travelDate'] = $res['carPoolOrder']['details']['startDate'];
        $resOrder['username'] = $res['customer']['profile']['name'];
        $resOrder['userphone'] = $res['customer']['username'];
        $resOrder['email'] = $res['customer']['email']??"";
        $resOrder['serveAddress'] = $res['serveAddress']??"";
        $resOrder['carPoolOrder'] = $res['carPoolOrder']??[];
        $resOrder['largeLuggages'] = $res['largeLuggages']??0;
        $resOrder['childPassengers'] = $res['childPassengers']??0;
        $resOrder['adultPassengers'] = $res['adultPassengers']??0;
        $resOrder['note'] = $res['note']??'';
        $resOrder['serveAddress'] = $res['serveAddress']??'';
        $resOrder['wechat'] = $res['customer']['wechat']['number']??'';
        //汇率
        $exchangeArr = db("exchange")->select();
        if(!empty($exchangeArr)){
            $moneyArr = array();
            foreach ($exchangeArr as $k=>$v) {
                $v_money = $resOrder['foldMoney']/$v['exchange_rate'];
                $v_money = ceil($v_money*100)/100;
                $moneyArr[] = array("code"=>$v['currency_code'],"money"=>$v_money);
            }
        }
        $moneyArr[] = array("code"=>"CNY","money"=>$resOrder['foldMoney']);
        $resOrder['moneyArr'] = $moneyArr;

        return json_encode(['code'=>200,'msg'=>'success','data'=>$resOrder]);
    }

    //删除订单
    public function delOrder()
    {
        $post = request()->post();
        $order_id = $post['order_id'];
        $order_no = $post['order_no'];

        $KbxOrder = new KbxOrder();
        $res = $KbxOrder->kbx_order_by_no($order_no);
        if(!empty($res['msg'])) return json_encode(['code'=>-400,'msg'=>$res['msg']]);
        if($res['status']['paymentStatus']!=='paid'){
            //订单系统  更新order数据
            $postUpdateArr = [
                'id'=>$order_id,
                'isDelete'=>1,
            ];
            if($res['orderType']=="CarPool"){
                $update_res = $KbxOrder->deletePersonalCarPoolOrder($order_id);
            }elseif($res['orderType']=="CustomMade"){
                $update_res = $KbxOrder->deletePersonalCustomMadeOrder($order_no);
            }else{
                $update_res = $KbxOrder->kbx_operate_order($res['orderType'],$postUpdateArr);
            }
            $log[]=[
                '删除订单：删除成功'=>json_encode($postUpdateArr),
                'res'=>$update_res
            ];
            log::record($log);
            if(!empty($update_res['msg'])) return json_encode(['code'=>-400,'msg'=>$update_res['msg']]);

            return json_encode(['code'=>200,'msg'=>'订单删除成功']);
        }
        return json_encode(['code'=>-400,'msg'=>'订单已支付，不能删除！']);
    }

    //模拟微信支付订单
    public function testPayCarPoolOrder()
    {
        $post = request()->post();
        $order_id = $post['order_id'];
        $personal_order_id = $post['personal_order_id'];
        //拼团订单 更新支付状态
        $postUpdateArr = [
            "carPoolOrderId"=>$order_id,
            "personalCarPoolOrderId"=>$personal_order_id,
            'payType' => 1,//微信支付
        ];
        $update_res = (new KbxOrder())->kbx_operate_order("CarPool",$postUpdateArr);
        $update_res = json_decode($update_res,true);
        return json_encode($update_res);
    }

    //根据日期判断淡旺季
    public function getBusySeasonByDate()
    {
        $post = request()->post();
        //关键字
        $id = $post['id']??'';
        $date = $post['date']??'';

        if(empty($date)) return json_encode(['code'=>-400,'msg'=>'请选择日期！']);
        $line = db('group_tours_line')->find($id);
        if(empty($id) || empty($line)) return json_encode(['code'=>-400,'msg'=>'请选择日期！']);
        $city = db('city')->find($line['city_id']);
        if(empty($line['city_id']) || empty($city) || empty($city['kbx_id'])){
            //发送报警邮件
            (new Common())->sendNoticeMailToKbx('拼游产品：'.$id.',缺少关联城市');
            return json_encode(['code'=>-400,'msg'=>'请求错误！请稍后再试']);
        }

        $KbxOther = new KbxOther();
        $res = $KbxOther->isBusySeasonByDate(['city'=>$city['kbx_id'],'startAt'=>$date]);
        if(!empty($res['msg'])) return json_encode(['code'=>-400,'msg'=>$res['msg']]);
        return json_encode(['code'=>200,'msg'=>'success','data'=>$res]);
    }

    //封装下单用户信息
    protected function packageBooker($groupInfo)
    {
        $bookers = [];
        $customers = $groupInfo['customers']??[];
        if(empty($customers)) return $groupInfo;
        foreach ($customers as $key=>$value){
            $childPassengers = $value['childPassengers'];
            $adultPassengers = $value['adultPassengers'];
            $bookerFaceImg = $value['booker']['user']['thumb']??'';
            $bookerFaceImg = str_replace('http://','https://',$bookerFaceImg);
            $bookerFaceImg = empty($bookerFaceImg)?Config::get('default_member_headimg'):$bookerFaceImg;
            $bookers[] = [
                'passengers'=>$childPassengers+$adultPassengers,
                'childPassengers'=>$childPassengers,
                'adultPassengers'=>$adultPassengers,
                'bookerMemberId'=>$value['booker']['memberId']??0,
                'bookerNickname'=>$value['booker']['user']['profile']['name']??'',
                'bookerFaceImg'=>$bookerFaceImg,
            ];
        }
        unset($groupInfo['customers']);
        $groupInfo['bookers'] = $bookers;
        return $groupInfo;
    }

    //计算下单用户返现金额
    protected function calculateCashBackByPartySize($groupInfo)
    {
        //获取当前的套餐和返现规则
        $line_id = $groupInfo['line']??0;
        $detail = db('group_tours_line g')
            ->field('person_price,currency')
            ->find($line_id);
        if(empty($line_id) || empty($detail)) return $groupInfo;
        if(empty($groupInfo['bookers'])) return $groupInfo;

        $model = new GT();
        $cashBackRules = $model->getCashBackRules($detail['person_price'],$line_id);
        //获取每人返现的金额
        $cashBack = 0;
        if($groupInfo['currentPartySize'] > 0){
            foreach ($cashBackRules as $p_k=>$p_v){
                $cashBack = $p_v['cashBack'];
                if($p_v['people_num'] == $groupInfo['currentPartySize']){
                    break;
                }
            }
        }
        foreach ($groupInfo['bookers'] as $b_k=>$b_v){
            $groupInfo['bookers'][$b_k]['cashBack'] = $b_v['passengers']*$cashBack;
            $groupInfo['bookers'][$b_k]['currency'] = $detail['currency'];
        }

        return $groupInfo;
    }

    //------------------------------ 自由拼游接口 ----------------------------------------
    //自由拼产品列表
    public function freeGroupLineList()
    {
        $post = request()->post();
        $page = $post['page']??1;
        $offset = $post['offset']??10;
        $keyword = $post['keyword']??"";
        $model = new FG();
        list($total,$list) = $model->getLineList($keyword,$page,$offset);
        $data['total'] = $total;
        $data['totalPage'] = ceil($total/$offset);
        $data['curPage'] = (int)$page;
        $data['offset'] = (int)$offset;
        $data['list'] = $list;
        return json_encode(['code'=>200,'msg'=>'success','data'=>$data]);

    }

    //自由拼 团列表
    public function freeGroupList()
    {
        $post = request()->post();
        $page = $post['page']??1;
        $offset = $post['offset']??10;
        $keyword = $post['keyword']??"";
        $model = new FG();
        list($total,$list) = $model->getList($keyword,$page,$offset);
        foreach ($list as $key=>$value){
            $list[$key]['status_title'] = $this->getFreeGroupStatusTitle($value['status'],true);
        }
        $data['total'] = $total;
        $data['totalPage'] = ceil($total/$offset);
        $data['curPage'] = (int)$page;
        $data['offset'] = (int)$offset;
        $data['list'] = $list;
        return json_encode(['code'=>200,'msg'=>'success','data'=>$data]);
    }

    //自由拼 团详情
    public function freeGroupInfo()
    {
        $post = request()->post();
        $id = $post['id']??0;
        $member_id = $post['member_id']??0;
        $free_group = db('free_group fg')
            ->field('fg.id,grouptour_id,free_title,free_desc,fg.remark,
            fg.start_city,fg.end_city,start_date,meet_address,
            max_people_num,cur_people_num,fg.status,
            s.name as start_city_name,e.name as end_city_name')
            ->join('city s','fg.start_city=s.id','left')
            ->join('city e','fg.end_city=e.id','left')
            ->where(['fg.is_deleted'=>0,'fg.id'=>$id])->find();
        if(empty($id) || empty($free_group)) return json_encode(['code'=>-400,'msg'=>'未查询到信息']);
        $free_group['status_title'] = $this->getFreeGroupStatusTitle($free_group['status'],true);
        $free_group['start_city_name'] = $free_group['start_city_name']?:'';
        $free_group['end_city_name'] = $free_group['end_city_name']?:'';
        //获取发起者
        $ownerMember = db('free_group_member fgm')
            ->join('member m','m.member_id=fgm.member_id','left')
            ->join('attachment a','m.thumb=a.id','left')
            ->field('fgm.id,fgm.free_group_id,fgm.member_id,fgm.country_code,phone,email,wechat,
            people_num,fgm.status,is_owner,m.member_nickname,a.filepath as headimg')->where([
            'free_group_id'=>$id,
            'fgm.is_owner'=>1
        ])->find();
        //获取参与者
        $joinMemberList = db('free_group_member fgm')
            ->join('member m','m.member_id=fgm.member_id','left')
            ->join('attachment a','m.thumb=a.id','left')
            ->field('fgm.id,fgm.free_group_id,fgm.member_id,fgm.country_code,phone,email,wechat,
            people_num,fgm.status,is_owner,m.member_nickname,a.filepath as headimg')->where([
                'free_group_id'=>$id,
                'fgm.status'=>['in',[1,2]]
            ])->select();
        foreach ($joinMemberList as $key=>$value){
            //获取拼团状态
            $joinMemberList[$key]['status_title'] = $this->getFreeGroupStatusTitle($value['status']);
            //隐藏用户昵称
            $joinMemberList[$key]['member_nickname'] = (new Common())->hideLongStringMiddlePart($value['member_nickname']);
        }
        //获取发起者
        foreach ($joinMemberList as $value){
            if($value['is_owner']==1){
                $ownerMember = $value;
                break;
            }
        }
        //若用户登陆且已报名则显示状态
        $free_group['is_join'] = false;
        $free_group['join_id'] = 0;
        $free_group['is_owner'] = false;
        if(!empty($joinMemberList) && !empty($member_id)){
            $member_ids = array_column($joinMemberList,'member_id');
            $join_ids = array_column($joinMemberList,'id');
            if(in_array($member_id,$member_ids)){
                $free_group['is_join'] = true;
                $free_group['join_id'] = $join_ids[array_search($member_id,$member_ids)];
            }
            if($member_id==$ownerMember['member_id']){
                $free_group['is_owner'] = true;
            }
        }
        if(!$free_group['is_owner']){
            foreach ($joinMemberList as $key=>$value){
                $joinMemberList[$key]['phone'] = substr_replace($value['phone'],'****',4,4);
                $joinMemberList[$key]['status_title'] = $this->getFreeGroupStatusTitle($value['status']);
            }
        }
        $ownerMember['phone'] = $free_group['is_join']?$ownerMember['phone']:substr_replace($ownerMember['phone'],'****',4,4);
        $data['groupInfo'] = $free_group;
        $data['ownerInfo'] = $ownerMember;
        $data['joinMemberlist'] = $joinMemberList;
        return json_encode(['code'=>200,'msg'=>'success','data'=>$data]);
    }

    //发起自由拼
    public function createFreeGroup()
    {
        $post = request()->post();
        $post['owner_id'] = $this->member_id;
        $model = new FG();
        //验证  唯一规则： 表名，字段名，排除主键值，主键名
        $validate = new \think\Validate([
//            ['grouptour_id', 'require', '请选择关联产品'],暂时不关联产品
            ['free_title', 'require', '拼游主题不能为空'],
            ['free_desc', 'require', '请填写行程简介'],
            ['start_date', 'require', '请填写出发日期'],
            ['start_city', 'require', '请选择出发城市'],
            ['end_city', 'require', '请选择目的地城市'],
            ['max_people_num', 'require', '请填写最大招募人数'],
            ['country_code', 'require', '请选择区号'],
            ['phone', 'require', '请填写手机号'],
        ]);
        if(empty($post['grouptour_id'])){
            //获取默认的线路id
            $grouptourline = db('group_tours_line')->where(['is_free'=>1])->find();
            if(empty($grouptourline)){
                $grouptourline = db('group_tours_line')->find();
            }
            $post['grouptour_id'] = $grouptourline['line_id'];
        }
        //验证部分数据合法性
        if (!$validate->check($post)) {
            return json_encode(['code'=>-400,'msg'=>$validate->getError()]);
        }
        $res = $this->checkCreateFreeGroupByOneOwner($post['start_date'],$post['owner_id']);
        if(!empty($res)){
            return json_encode(['code'=>-400,'msg'=>'您在【'.$post['start_date'].'】已经创建过拼游，每个用户同一天只能创建一个拼游。']);
        }
        $res = $this->checkFreeGroupByOneOwnerOneMinute($post);
        if(!empty($res)){
            return json_encode(['code'=>-400,'msg'=>'您已经在【'.$post['start_date'].'】创建过类似的拼游！']);
        }
        //发起自由拼
        db::startTrans();
        try{
            $post['create_time'] = $post['update_time'] = time();
            $post['cur_people_num'] = empty($post['people_num'])?1:$post['people_num'];
            $model->allowField(true)->save($post);
            //获取当前发起的团id
            $post['free_group_id'] = db()->getLastInsID();
            $post['people_num'] = $post['cur_people_num'];
            $post['member_id'] = $post['owner_id'];
            $post['is_owner'] = 1;//发起者
            //加入拼游
            $this->addMemberToFreeGroup($post);
            //发送订阅消息
            (new Unionid())->sendFreeGroupDataToSubscribeMessage($post['free_group_id'],$post['member_id'],1);
            db::commit();
            return json_encode(['code'=>200,'msg'=>'发起成功','data'=>['free_group_id'=>$post['free_group_id']]]);
        }catch(Exception $e){
            db::rollback();
            //发送警告
            $content = "请求体：".json_encode($post).',错误信息：'.$e->getMessage();
            trace($content);
            (new Common())->sendNoticeMailToKbx('创建自由拼失败',$this->notice_email,$content);
            return json_encode(['code'=>-400,'msg'=>'发起自由拼失败，请稍后重试']);
        }
    }

    //加入自由拼
    public function joinFreeGroup()
    {
        $post = request()->post();
        //检验必须参数 to do ...
        $match_arr = array(
            "free_group_id",
            "country_code",
            "phone",
            "people_num"
        );
        $match_res = (new WapGT())->match_post($match_arr,$post);
        if($match_res['code']!=200){
            return json_encode($match_res);
        }
        $post['member_id'] = $this->member_id;
        //检查是否存在
        $free_group = db('free_group')->find($post['free_group_id']);
        if(empty($free_group)) return json_encode(['code'=>-400,'msg'=>'未查询到该信息']);
        $res = $this->checkJoinFreeGroupByOneMember($post['free_group_id'],$post['member_id']);
        if(!empty($res)){
            return json_encode(['code'=>-400,'msg'=>'您已参与过此次拼游，请勿重复报名']);
        }
        db::startTrans();
        try{
            //加入拼游
            $this->addMemberToFreeGroup($post);
            //修改当前拼游的人数
            $this->updateFreeGroupCurPeopleNum($post['free_group_id'],$post['people_num'],'inc');
            //发送订阅消息给发起者
            (new Unionid())->sendFreeGroupDataToSubscribeMessage($post['free_group_id'],$free_group['owner_id'],11);
            //发送订阅消息给参与者
            (new Unionid())->sendFreeGroupDataToSubscribeMessage($post['free_group_id'],$post['member_id'],12);
            db::commit();
            return json_encode(['code'=>200,'msg'=>'加入成功','data'=>['free_group_id'=>$post['free_group_id']]]);
        }catch(Exception $e){
            db::rollback();
            //发送警告
            $content = "请求体：".json_encode($post).',错误信息：'.$e->getMessage();
            trace($content);
            (new Common())->sendNoticeMailToKbx('创建自由拼失败',$this->notice_email,$content);
            return json_encode(['code'=>-400,'msg'=>'加入自由拼失败，请稍后重试']);
        }
    }

    //获取城市列表
    public function getFreeGroupCityList()
    {
        $list = (new Common())->getSoftCityList();
        return json_encode(['code'=>200,'msg'=>'success','data'=>$list]);
    }

    //取消自由拼游 【发起人取消 直接取消该拼游】
    public function outFreeGroup()
    {
        $post = request()->post();
        //检验必须参数 to do ...
        $match_arr = array(
            "id"
        );
        $match_res = (new WapGT())->match_post($match_arr,$post);
        if($match_res['code']!=200){
            return json_encode($match_res);
        }
        $post['member_id'] = $this->member_id;
        //当前用户报名的id
        $id = $post['id'];
        //查询是否存在参团记录
        $free_group_member = db('free_group_member')->find($id);
        if(empty($free_group_member)) return json_encode(['code'=>-400,'msg'=>'暂未查询到该记录']);
        if($free_group_member['member_id']!=$post['member_id']) return json_encode(['code'=>-400,'msg'=>'对不起，您无操作权限']);
        if($free_group_member['status']>1) return json_encode(['code'=>-400,'msg'=>'对不起，拼游状态已不能取消']);
        $free_group = db('free_group')->find($free_group_member['free_group_id']);
        db::startTrans();
        try{
            $joinMemberList = db('free_group_member')
                ->where([
                    'free_group_id'=>$free_group_member['free_group_id'],
                    'is_deleted'=>0,
                    'status'=>1,
                    'is_owner'=>0,
                ])->select();
            //如果是发起人退出则直接去取消当前团
            if($free_group_member['is_owner']==1){
                db('free_group')->where('id',$free_group_member['free_group_id'])->update(['status'=>10]);
                //取消所有参团人的报明状态
                db('free_group_member')->where('free_group_id',$free_group_member['free_group_id'])->update(['status'=>10]);
                //发送订阅消息给发起者
                (new Unionid())->sendFreeGroupDataToSubscribeMessage($free_group_member['free_group_id'],$free_group['owner_id'],21);
                //发送邮件到每个人的邮箱
                foreach ($joinMemberList as $value){
                    $content = "发起人取消了【出发日期为".$free_group['start_date']."的".$free_group['free_title']."】的自由行。";
                    if(!empty($email)) $this->sendEmailToMember($value['email'],$content);
                    //发送订阅消息给参与者
                    (new Unionid())->sendFreeGroupDataToSubscribeMessage($free_group_member['free_group_id'],$value['member_id'],22);
                }
            }else{
                //直接修改当前的参与状态为退出
                db('free_group_member')->where('id',$id)->update(['status'=>10]);
                //更新当前的报名人数
                $this->updateFreeGroupCurPeopleNum($free_group_member['free_group_id'],$free_group_member['people_num'],'dec');
                //发送订阅消息给参与者
                (new Unionid())->sendFreeGroupDataToSubscribeMessage($free_group_member['free_group_id'],$free_group_member['member_id'],24);
                //发送邮件到发起人的邮箱
                $member = db('member')->find($post['member_id']);
                $content = "用户".$member['member_nickname']."取消了【出发日期为".$free_group['start_date']."的".$free_group['free_title']."】的自由行。";
                $free_group_owner = db('free_group_member')->where('is_owner',1)->find();
                if(!empty($free_group_owner['email'])) $this->sendEmailToMember($free_group_owner['email'],$content);
                //发送订阅消息给发起者
                (new Unionid())->sendFreeGroupDataToSubscribeMessage($free_group_member['free_group_id'],$free_group['owner_id'],23);
            }
            db::commit();
            return json_encode(['code'=>200,'msg'=>'退出成功']);
        }catch(Exception $e){
            db::rollback();
            trace("取消自由拼失败，错误信息：".$e->getMessage());
            return json_encode(['code'=>-400,'msg'=>'修改失败，请稍后再试']);
        }
    }

    //获取用户的拼游列表
    public function freeGroupListByMemberId()
    {
        $post = request()->post();
        $post['member_id'] = $this->member_id;
        $page = $post['page']??1;
        $offset = $post['offset']??10;
        //查询自己的拼游列表
        $where['m.member_id'] = $post['member_id'];
        $where['m.is_deleted'] = 0;
        if(!empty($post['owner'])){
            $where['m.is_owner'] = 1;
        }
        $model = new FreeGroupMember();
        $total = $model->name('free_group_member m')->where($where)->count();
        $list = $model->name('free_group_member m')
            ->join('free_group g','g.id=m.free_group_id','left')
            ->join('city s','s.id=g.start_city','left')
            ->join('city e','e.id=g.end_city','left')
            ->where($where)
            ->field('g.free_title,g.free_desc,g.remark,g.start_date,g.meet_address,
            g.max_people_num,g.cur_people_num,g.start_city,g.end_city,g.status as g_status,m.status, 
            s.name as start_city_name,e.name as end_city_name,
            m.free_group_id,m.country_code,m.phone,m.email,m.wechat,
            m.create_time,m.is_owner,m.people_num')
            ->order('m.create_time desc')
            ->page($page,$offset)->select();
        foreach ($list as $key=>$value){
            //获取拼团状态
            $list[$key]['g_status_title'] = (new GroupToursWxSoft())->getFreeGroupStatusTitle($value['g_status'],true);
            $list[$key]['status_title'] = (new GroupToursWxSoft())->getFreeGroupStatusTitle($value['status']);
            $list[$key]['start_city_name'] = $value['start_city_name']?:'';
            $list[$key]['end_city_name'] = $value['end_city_name']?:'';
        }
        $data['total'] = $total;
        $data['totalPage'] = ceil($total/$offset);
        $data['curPage'] = (int)$page;
        $data['offset'] = (int)$offset;
        $data['list'] = $list;
        return json_encode(['code'=>200,'msg'=>'success','data'=>$data]);
    }

    //加入拼游
    protected function addMemberToFreeGroup($data)
    {
        $upd_data = [
            'free_group_id'=>$data['free_group_id'],
            'member_id'=>$data['member_id'],
            'country_code'=>$data['country_code']??"",
            'phone'=>$data['phone']??"",
            'email'=>$data['email']??"",
            'wechat'=>$data['wechat']??"",
            'people_num'=>$data['people_num'],
            'create_time'=>time(),
            'update_time'=>time(),
            'status'=>1,
            'is_deleted'=>0,
            'is_owner'=>$data['is_owner']??0,
        ];
        //查询是否报名过当前拼游
        $is_exist = db('free_group_member')->where([
            'free_group_id'=>$data['free_group_id'],
            'member_id'=>$data['member_id']
        ])->find();
        if(!empty($is_exist)){
            $res = db('free_group_member')->where('id',$is_exist['id'])->update($upd_data);
        }else{
            $res = db('free_group_member')->insert($upd_data);
        }
        return $res;
    }

    //修改当前自由拼团的参与人数
    protected function updateFreeGroupCurPeopleNum($id,$num=1,$type='inc')
    {
        if($type=='inc'){
            db('free_group')->where('id',$id)->setInc('cur_people_num',$num);
        }else{
            db('free_group')->where('id',$id)->setDec('cur_people_num',$num);
        }
    }

    //发送取消拼游的邮件
    protected function sendEmailToMember($email,$content="")
    {
        $subject = "自由行取消通知";
        if((new Common())->checkFreeGroupSendNoticeEmail()){
            (new Common())->sendNoticeMailToKbx($subject,$email,$content);
        }
    }

    //获取自由拼的状态 group为true 表示为团状态
    public function getFreeGroupStatusTitle($status,$group=false)
    {
        $title = "";
        switch ($status){
            case 1:
                $title = "拼游中";break;
            case 2:
                $title = "已完成";break;
            case 10:
                $title = $group?"已解散":"已取消";break;
            default:
                $title = "拼游中";break;
        }

        return $title;
    }

    //是否允许同一用户创建同一天的不同活动
    protected function checkCreateFreeGroupByOneOwner($date,$owner_id)
    {
        //20200715特殊账号处理 小飞账号不限制
        if(in_array($owner_id,[190])) return false;
        $result = db('free_group')
            ->where([
                'start_date'=>$date,
                'owner_id'=>$owner_id,
                'status'=>1
            ])
            ->find();
        return $result;
    }
    //同一用户一分钟内创建类似订单返回错误
    protected function checkFreeGroupByOneOwnerOneMinute($post)
    {
        //限制时长 单位秒
        $limit_min = 60;
        $result = db('free_group')
            ->where([
                'start_date'=>$post['start_date']??'',
                'free_title'=>$post['free_title']??'',
                'start_city'=>$post['start_city']??'',
                'end_city'=>$post['end_city']??'',
                'owner_id'=>$post['owner_id']??0,
                'status'=>1,
                'create_time'=>['gt',time()-$limit_min]
            ])
            ->find();
        return $result;
    }

    //是否允许同一用户多次参与同一活动
    protected function checkJoinFreeGroupByOneMember($free_group_id,$member_id)
    {
        $result = db('free_group_member')
            ->where([
                'free_group_id'=>$free_group_id,
                'member_id'=>$member_id,
                'status'=>1
            ])->find();
        return $result;
    }

    //提交拼游微信小程序的反馈意见
    public function createGrouptourFeedback()
    {
        $post = request()->post();
        $model = new WxsoftGrouptourFeedback();
        //验证  唯一规则： 表名，字段名，排除主键值，主键名
        $validate = new \think\Validate([
            ['email', 'require', '请填写邮箱地址'],
            ['feedback_content', 'require', '请填写反馈意见'],
        ]);

        //验证部分数据合法性
        if (!$validate->check($post)) {
            return json_encode(['code'=>-400,'msg'=>$validate->getError()]);
        }
        $res = $model->allowField(true)->save($post);
        if($res){
            return json_encode(['code'=>200,'msg'=>'提交成功','data'=>['feedback_id'=>db()->getLastInsID()]]);
        }else{
            return json_encode(['code'=>-400,'msg'=>'提交失败，请稍后重试']);
        }
    }

    //判断团期是否属于旺季
    public function checkIsBusyByGroupInfo($groupInfo)
    {
        $startDate = $groupInfo['details']['startDate']??'';
        $city_id = $groupInfo['details']['fromCity']??'';
        if(empty($startDate) || empty($city_id)) return false;
        $KbxOther = new KbxOther();
        $res = $KbxOther->isBusySeasonByDate(['city'=>$city_id,'startAt'=>$startDate]);
        return $res['isBusySeason']??false;
    }

    //过期拼游定时修改状态
    public function updateFreeGroupStatus()
    {
        ignore_user_abort();//关闭浏览器仍然执行
        set_time_limit(0);//让程序一直执行下去
        log::log('修改自由拼状态开始');
        $list = db('free_group')->where(['status'=>1,'start_date'=>['lt',date('Y-m-d')]])->select();
        if(empty($list)){
            log::log('修改自由拼状态结束，暂无任何更新');
            return json_encode(['code'=>200,'msg'=>'no data update']);
        }
        db::startTrans();
        try{
            foreach ($list as $key=>$value){
                db('free_group_member')->where('free_group_id',$value['id'])->update(['status'=>2,'update_time'=>time()]);
                db('free_group')->where('id',$value['id'])->update(['status'=>2,'update_time'=>time()]);
                log::log('已完成的自由拼id：'.$value['id']);
            }
            db::commit();
            log::log('修改自由拼状态结束');
            return json_encode(['code'=>200,'msg'=>'success']);
        }catch(Exception $e){
            db::rollback();
            log::log('过期拼游定时修改状态失败,失败原因是'.$e->getMessage());
            return json_encode(['code'=>400,'msg'=>'fail']);
        }
    }

    //-------------------------------新版小V拼游--------------------------------
    //发布拼游信息【人找车、车找人】
    public function publishFreeGroup()
    {
        $post = request()->post();
        $post['owner_id'] = $this->member_id;
        $model = new FG();
        //验证  唯一规则： 表名，字段名，排除主键值，主键名
        $validate = new \think\Validate([
//            ['grouptour_id', 'require', '请选择关联产品'],暂时不关联产品
//            ['free_title', 'require', '拼游主题不能为空'],
//            ['free_desc', 'require', '请填写行程简介'],
            ['type', 'require', '请选择拼游类型'],
            ['start_city', 'require', '请选择始发地'],
            ['end_city', 'require', '请选择目的地'],
            ['start_date', 'require', '请填写出发日期'],
            ['max_people_num', 'require', '请填写车辆总人数'],
            ['cur_people_num', 'require', '请填写车辆空位'],
            ['country_code', 'require', '请选择区号'],
            ['phone', 'require', '请填写手机号'],
        ]);
        $typeName = (new FG())->getFreeGroupTypeName($post['type']);
        if(empty($post['grouptour_id'])){
            //获取默认的线路id
            $grouptourline = db('group_tours_line')->where(['is_free'=>1])->find();
            if(empty($grouptourline)){
                $grouptourline = db('group_tours_line')->find();
            }
            $post['grouptour_id'] = $grouptourline['line_id'];
        }
        //验证部分数据合法性
        if (!$validate->check($post)) {
            return json_encode(['code'=>-400,'msg'=>$validate->getError()]);
        }
        $res = $this->checkCreateFreeGroupByOneOwner($post['start_date'],$post['owner_id'],$post['type']);
        if(!empty($res)){
            return json_encode(['code'=>-400,'msg'=>'您在【'.$post['start_date'].'】已经创建过'.$typeName.'，每个用户同一天只能创建一个拼游。']);
        }
        $res = $this->checkFreeGroupByOneOwnerOneMinute($post);
        if(!empty($res)){
            return json_encode(['code'=>-400,'msg'=>'您已经在【'.$post['start_date'].'】创建过类似的'.$typeName.'！']);
        }
        //发起自由拼
        db::startTrans();
        try{
            $post['create_time'] = $post['update_time'] = time();
            $post['cur_people_num'] = empty($post['cur_people_num'])?1:$post['cur_people_num'];
            $model->allowField(true)->save($post);
            //获取当前发起的团id
            $post['free_group_id'] = db()->getLastInsID();
            $post['people_num'] = $post['cur_people_num'];
            $post['member_id'] = $post['owner_id'];
            $post['is_owner'] = 1;//发起者
            //加入拼游
            $this->addMemberToFreeGroup($post);
            //发送订阅消息
            (new Unionid())->sendFreeGroupDataToSubscribeMessage($post['free_group_id'],$post['member_id'],1);
            db::commit();
            return json_encode(['code'=>200,'msg'=>'发起成功','data'=>['free_group_id'=>$post['free_group_id']]]);
        }catch(Exception $e){
            db::rollback();
            //发送警告
            $content = "请求体：".json_encode($post).',错误信息：'.$e->getMessage();
            trace($content);
            (new Common())->sendNoticeMailToKbx('创建'.$typeName.'失败',$this->notice_email,$content);
            return json_encode(['code'=>-400,'msg'=>'发起失败，请稍后重试']);
        }

    }

}